<script setup lang="ts">
  import CenterHeader from './center/centerHeader.vue';
  import Left from './newleft/index.vue';
  import Right from './right/index.vue';
  import { ElContainer, ElMessage } from 'element-plus';
  import ReceiveMessage from '/@/core/communication/ReceiveMessage';
  import { Platform, ReceiveMessageType, SendMessageType } from '/@/config/DeclareGlobal';
  import { computed, onMounted, ref } from 'vue';
  import { useRouter } from 'vue-router';
  import sendToUnity from '/@/core/communication/SendToUnity';
  import {
    getAssetProfileId,
    getDeviceProfilesId,
  } from '/@/views/DigitalTwin/newleft/service/defaultId';
  import { useStore } from 'vuex';
  import {
    addBasicDeviceParams,
    deviceInfoItem,
    relationResponse,
    saveAssetParams,
    saveAttributesParams,
    saveRelationParams,
    saveTelemetryParams
  } from '/@/api/thingsborad/entity/model/entityModel';
  import {
    createDevice,
    getDevice,
    getDeviceInfo,
    saveAsset,
    saveEntityAttributes,
    saveEntityTelemetry,
    saveRelation,
  } from '/@/api/thingsborad/entity/entity';
  import { deleteAllDevices } from '/@/views/DigitalTwin/newleft/service/delete';
  // 导入 Node-RED 相关功能
  import {
    connectToNodeRed,
    sendToNodeRed,
    handleTaskComplete,
    setupPageVisibilityListener,
    setEnvironmentMode,
  } from '/@/core/communication/nodered';

  const store = useStore();
  const queue: Function[] = [];
  let totalDevices: { [key: string]: { [key: string]: any } } | null = {};

  /*setInterval(() => {
  if (queue.length > 0) {
    queue[queue.length - 1]();
    queue.pop();
  }
}, 500);*/
  // 存储按键状态
  const keysPressed = {
    ctrl: false,
    m: false,
    i: false,
  };

  //监听按键ctrl+l+i
  document.addEventListener('keydown', (event) => {
    // 更新按键状态
    if (event.key === 'Control') keysPressed.ctrl = true;
    if (event.key === 'm' || event.key === 'M') keysPressed.m = true;
    if (event.key === 'i' || event.key === 'I') keysPressed.i = true;

    // 检查组合键
    if (keysPressed.ctrl && keysPressed.m && keysPressed.i) {
      // console.log('Ctrl + L + I pressed!');
      createTotalManageAsset();
      // 执行你的操作（例如打开设置面板）
      // 重置状态防止连续触发
      keysPressed.m = false;
      keysPressed.i = false;
    }
  });

  document.addEventListener('keyup', (event) => {
    // 按键释放时重置状态
    if (event.key === 'Control') keysPressed.ctrl = false;
    if (event.key === 'm' || event.key === 'M') keysPressed.m = false;
    if (event.key === 'i' || event.key === 'I') keysPressed.i = false;
  });

  const iframeRef = ref<HTMLIFrameElement | null>(null);

  const showGlobalTitle = ref(true);
  const globalTitle = ref('锂电池工厂');

  // 计算iframe的src地址
  const iframeSrc = computed(() => {
    const host =
      process.env.NODE_ENV === 'development' ? window.location.hostname : window.location.hostname;
    return `http://${host}:9000/`;
  });

  // 接收来自左侧菜单的事件
  const handleTitleChange = (newTitle: string) => {
    globalTitle.value = newTitle;
    showGlobalTitle.value = true;
  };

  const isWebGL = ref(true); // 默认使用WebGL模式
  const environmentMode = ref('webgl'); // 当前环境模式

  // 监听键盘事件
  function setupKeyboardListener() {
    document.addEventListener('keydown', (event) => {
      // 按U键切换环境模式
      if (event.key === 'u' || event.key === 'U') {
        isWebGL.value = !isWebGL.value;
        environmentMode.value = isWebGL.value ? 'webgl' : 'unity';
        // 更新 Node-RED 模块中的环境模式
        setEnvironmentMode(isWebGL.value);
        console.log(`已切换到 ${environmentMode.value} 模式`);

        // 如果切换到Unity模式，显示提示消息
        if (!isWebGL.value) {
          ElMessage.info({
            message: '已切换到Unity模式',
            duration: 2000,
          });
        }
      }
    });
  }

  onMounted(async () => {
    setupKeyboardListener();
    setupPageVisibilityListener();
    if (iframeRef.value) {
      try {
        sendToUnity.init(iframeRef.value);
        console.log('SendToUnity 初始化成功！');
      } catch (error) {
        console.error('初始化失败：');
      }
    } else {
      console.error('iframeRef 未找到，请检查 DOM 元素。');
    }

    showGlobalTitle.value = true;
    globalTitle.value = '锂电池工厂';
    deviceProfileIdValue = await getDeviceProfilesId();
    // 创建Node-RED WebSocket连接
    connectToNodeRed();
  });
  let deviceProfileIdValue = '';
  ReceiveMessage.addListener(ReceiveMessageType.TrayFlow, async (e: any) => {
    // console.log('流量统计：', e);

    // 解析数据
    const data = JSON.parse(e.data);

    // 遍历segs数组，为每个seg创建设备并保存遥测数据
    for (const seg of data.segs) {
      try {
        // 创建或获取设备
        const deviceName = seg.segID;
        let device;

        try {
          device = await getDevice(deviceName);
        } catch (error) {
          // 设备不存在，设置为null以便后续创建
          device = null;
        }

        // 检查设备是否已存在
        const selectedNodes = computed(() => store.state.nodeData?.map((item) => item.toName));
        const toNames = selectedNodes.value || [];
        const isDeviceExist = toNames.includes(deviceName);

        // 如果设备不存在，则创建设备
        if (!isDeviceExist || !device || !device.id) {
          const deviceParams: addBasicDeviceParams = {
            name: deviceName,
            label: seg.segName,
            deviceProfileId: {
              entityType: 'DEVICE_PROFILE',
              id: '3a876720-aa60-11f0-9eff-a956e14e04e3', // Flow设备配置
            },
            additionalInfo: {
              gateway: false,
              overwriteActivityTime: false,
              description: `Flow设备 - ${seg.segName}`,
            },
            customerId: null,
          };

          device = await createDevice(deviceParams);

          // 如果有选中的资产，建立关联关系
          const selectedItemId = computed(() => store.state.selectedIssue?.to.id);
          if (selectedItemId.value) {
            const relationParams: saveRelationParams = {
              type: 'Contains',
              additionalInfo: {},
              typeGroup: 'COMMON',
              from: {
                entityType: 'ASSET',
                id: selectedItemId.value, // 父级资产ID
              },
              to: device.id,
            };
            await saveRelation(relationParams);
          }
        }

        // 保存遥测数据（无论设备是否已存在）
        const telemetryData = {
          curCount: seg.curCount,
          loaded: seg.loaded,
          empty: seg.empty,
          total: seg.total,
          flow: seg.flow,
          time: seg.time,
          instanceCount: seg.instanceCount
        };

        // 为每个遥测字段发送数据
        for (const [key, value] of Object.entries(telemetryData)) {
          await saveEntityTelemetry({
            entityType: 'DEVICE',
            entityId: device.id.id,
            key: key,
            value: value
          });
        }

        console.log(`设备 ${deviceName} 的遥测数据保存成功`);
      } catch (error) {
        console.error(`处理设备 ${seg.segID} 数据时出错:`, error);
      }
    }

    // 保存总计数据（如果需要的话）
    try {
      const totalDataDeviceName = 'TotalTrayFlow';
      let totalDevice;

      try {
        totalDevice = await getDevice(totalDataDeviceName);
      } catch (error) {
        // 设备不存在，设置为null以便后续创建
        totalDevice = null;
      }

      // 检查设备是否已存在
      const selectedNodes = computed(() => store.state.nodeData?.map((item) => item.toName));
      const toNames = selectedNodes.value || [];
      const isDeviceExist = toNames.includes(totalDataDeviceName);

      if (!isDeviceExist || !totalDevice || !totalDevice.id) {
        const deviceParams: addBasicDeviceParams = {
          name: totalDataDeviceName,
          label: '总托盘流量统计',
          deviceProfileId: {
            entityType: 'DEVICE_PROFILE',
            id: '4accdac0-aa6a-11f0-9eff-a956e14e04e3', // TotalFlow设备配置
          },
          additionalInfo: {
            gateway: false,
            overwriteActivityTime: false,
            description: '总托盘流量统计数据',
          },
          customerId: null,
        };

        totalDevice = await createDevice(deviceParams);

        // 如果有选中的资产，建立关联关系
        const selectedItemId = computed(() => store.state.selectedIssue?.to.id);
        if (selectedItemId.value) {
          const relationParams: saveRelationParams = {
            type: 'Contains',
            additionalInfo: {},
            typeGroup: 'COMMON',
            from: {
              entityType: 'ASSET',
              id: selectedItemId.value, // 父级资产ID
            },
            to: totalDevice.id,
          };
          await saveRelation(relationParams);
        }
      }

      // 保存总计遥测数据
      const totalTelemetryData = {
        totalTrays: data.totalTrays,
        totalLoaded: data.totalLoaded,
        totalEmpty: data.totalEmpty,
        totalFlow: data.totalFlow,
        time: data.time
      };

      for (const [key, value] of Object.entries(totalTelemetryData)) {
        await saveEntityTelemetry({
          entityType: 'DEVICE',
          entityId: totalDevice.id.id,
          key: key,
          value: value
        });
      }

      console.log('总计遥测数据保存成功');
    } catch (error) {
      console.error('处理总计数据时出错:', error);
    }
  });

  // 修改任务完成监听器
  ReceiveMessage.addListener(ReceiveMessageType.TaskComplete, (e: any) => {
    handleTaskComplete(e, isWebGL.value);
  });

  //创建一个资产将所有设备信息集合起来
  const createTotalManageAsset = async () => {
    const selectedIssueId: relationResponse = store.state.selectedIssue;
    const deviceName = `${selectedIssueId.toName}-设备总览`;
    let device: deviceInfoItem | null = null;

    const res = (device = await getDevice(deviceName));
    if (!res.id) {
      const deviceParams: addBasicDeviceParams = {
        name: deviceName,
        label: '资源管理',
        deviceProfileId: {
          entityType: 'DEVICE_PROFILE',
          id: '0bcee760-7e5e-11f0-a159-f9bfc56b8267', // Other           // 其他（未标记的物体）
        },
        additionalInfo: {
          gateway: false,
          overwriteActivityTime: true,
          description: '所有设备总览',
        },
        customerId: null,
      };
      device = await createDevice(deviceParams);
      const relationParams: saveRelationParams = {
        type: 'Contains',
        additionalInfo: {},
        typeGroup: 'COMMON',
        from: {
          entityType: 'ASSET',
          id: selectedIssueId.to.id, // 父级资产ID
        },
        to: device.id,
      };
      await saveRelation(relationParams);
    }
    if (totalDevices === null) return;
    //保存共享属性
    // for (const [key, value] of Object.entries(totalDevices)) {
    await saveEntityAttributes({
      entityType: 'DEVICE',
      entityId: device.id.id,
      scope: 'SHARED_SCOPE',
      key: 'AllDevices',
      value: totalDevices,
    });
    // }
    // totalDevices = null;
  };

  ReceiveMessage.addListener(ReceiveMessageType.InitDevice, async (e) => {
    const mData = e.data;
    const mDeviceInfo = mData;
    if (totalDevices === null) totalDevices = {};
    if (mDeviceInfo.DeviceType !== 3 && mDeviceInfo.DeviceType !== 4) {
      totalDevices[mDeviceInfo.Name] = {
        LocalScale: mDeviceInfo.LocalScale,
        Position: mDeviceInfo.Position,
        Rotation: mDeviceInfo.Rotation,
        Parent: mDeviceInfo.Parent,
        DeviceType: mDeviceInfo.DeviceType,
      };
      if (mDeviceInfo.StackerData) {
        const totalDevice = totalDevices[mDeviceInfo.Name];
        const stackerData = mDeviceInfo.StackerData;
        totalDevice['StackerDeviceID'] = stackerData.StackerDeviceID;
        totalDevice['TaskRow'] = stackerData.TaskRow;
        totalDevice['TaskColumn'] = stackerData.TaskColumn;
        totalDevice['TaskLevel'] = stackerData.TaskLevel;
        totalDevice['IsMoving'] = stackerData.IsMoving;
        totalDevice['IsMoveInPosition'] = stackerData.IsMoveInPosition;
        totalDevice['IsLifting'] = stackerData.IsLifting;
        totalDevice['IsExtending'] = stackerData.IsExtending;
        totalDevice['IsExtendComplete'] = stackerData.IsExtendComplete;
        totalDevice['IsTaskStarted'] = stackerData.IsTaskStarted;
        totalDevice['IsTaskFinished'] = stackerData.IsTaskFinished;
        totalDevice['AxisX_ActSpeed'] = stackerData.AxisX_ActSpeed;
        totalDevice['AxisY_ActSpeed'] = stackerData.AxisY_ActSpeed;
        totalDevice['AxisZ_ActSpeed'] = stackerData.AxisZ_ActSpeed;
      }
    }

    const fun: Function = async () => {
      try {
        const { data } = e;
        const deviceInfo = data;
        // 创建枚举值到字符串的映射，前面的ID为设备配置的ID
        const DeviceTypeMap = {
          0: '72154320-638d-11f0-baf1-1f027592f510', // Device,         // 实际设备
          1: 'e2bed1a0-7e5d-11f0-a159-f9bfc56b8267', // DevicePart,     // 设备部件
          2: 'fd9e3e70-7e5d-11f0-a159-f9bfc56b8267', // ParentGroup,    // 父组件（用于组织结构的空物体）
          3: '0615c140-7e5e-11f0-a159-f9bfc56b8267', // EmptyObject,    // 普通空物体
          4: '0bcee760-7e5e-11f0-a159-f9bfc56b8267', // Other           // 其他（未标记的物体）
        };

        // 转换设备类型（整数值 -> 字符串）
        const deviceTypeStr = DeviceTypeMap[deviceInfo.DeviceType];
        const selectedNodes = computed(() => store.state.nodeData?.map((item) => item.toName));
        const toNames = selectedNodes.value || [];
        // 检查设备是否已存在
        const isDeviceExist = toNames.includes(deviceInfo.Name);
        if (isDeviceExist) {
          console.log(`设备 ${deviceInfo.Name} 已存在，跳过创建`);
          return;
        }
        const deviceParams: addBasicDeviceParams = {
          name: deviceInfo.Name,
          label: deviceInfo.Name,
          deviceProfileId: {
            entityType: 'DEVICE_PROFILE',
            id: deviceTypeStr,
          },
          additionalInfo: {
            gateway: false,
            overwriteActivityTime: false,
            description: `${JSON.stringify(deviceInfo)}`,
          },
          customerId: null,
        };

        try {
          const device = await createDevice(deviceParams);
          const selectedItemId = computed(() => store.state.selectedIssue?.to.id);
          const relationParams: saveRelationParams = {
            type: 'Contains',
            additionalInfo: {},
            typeGroup: 'COMMON',
            from: {
              entityType: 'ASSET',
              id: selectedItemId.value, // 父级资产ID
            },
            to: device.id,
          };
          await saveRelation(relationParams);
          // 保存共享属性
          const attributes = [
            { key: 'LocalScale', value: deviceInfo.LocalScale },
            { key: 'Position', value: deviceInfo.Position },
            { key: 'Rotation', value: deviceInfo.Rotation },
            { key: 'Parent', value: deviceInfo.Parent },
            { key: 'DeviceType', value: deviceTypeStr },
          ];
          // 保存堆垛机特有属性（如果存在StackerData）
          if (deviceInfo.StackerData) {
            const stackerData = deviceInfo.StackerData;

            // 添加堆垛机所有属性（包括嵌套对象）
            attributes.push(
              { key: 'StackerDeviceID', value: stackerData.StackerDeviceID },
              { key: 'TaskRow', value: stackerData.TaskRow },
              { key: 'TaskColumn', value: stackerData.TaskColumn },
              { key: 'TaskLevel', value: stackerData.TaskLevel },
              { key: 'IsMoving', value: stackerData.IsMoving },
              { key: 'IsMoveInPosition', value: stackerData.IsMoveInPosition },
              { key: 'IsLifting', value: stackerData.IsLifting },
              { key: 'IsExtending', value: stackerData.IsExtending },
              { key: 'IsExtendComplete', value: stackerData.IsExtendComplete },
              { key: 'IsTaskStarted', value: stackerData.IsTaskStarted },
              { key: 'IsTaskFinished', value: stackerData.IsTaskFinished },

              // 处理嵌套对象属性
              { key: 'AxisX_ActSpeed', value: JSON.stringify(stackerData.AxisX_ActSpeed) },
              { key: 'AxisY_ActSpeed', value: JSON.stringify(stackerData.AxisY_ActSpeed) },
              { key: 'AxisZ_ActSpeed', value: JSON.stringify(stackerData.AxisZ_ActSpeed) },

              // 保存整个StackerData对象
              { key: 'StackerData', value: JSON.stringify(stackerData) },
            );
          }

          for (const attr of attributes) {
            // 显式声明参数对象并符合 saveAttributesParams 接口格式
            const attributesParams: saveAttributesParams = {
              entityType: 'DEVICE', // 设备类型
              entityId: device.id.id, // 设备ID
              scope: 'SHARED_SCOPE', // 共享属性作用域
              key: attr.key, // 属性名称
              value: attr.value, // 属性值（对象或原始值）
            };

            await saveEntityAttributes(attributesParams);
          }
          console.log(`设备 ${deviceInfo.Name} 创建成功`);
        } catch (error) {
          console.error(`创建设备 ${deviceInfo.Name} 失败:`, error);
        }
      } catch (error) {
        console.error(error);
      }
    };
    queue.push(fun);
  });

  ReceiveMessage.addListener(ReceiveMessageType.LogError, (e) => {
    const data = e.data;
    ElMessage.error(data);
  });

  const show_preview = ref(false);
  const handleOutsideClick = () => {
    // 点击外部区域执行的操作
  };
  const handleMouseEnter = () => {
    // 鼠标进入按钮时显示文本
    show_preview.value = true;
  };
  const handleMouseLeave = () => {
    // 鼠标离开按钮时隐藏文本
    show_preview.value = false;
  };
  const router = useRouter(); // 替换原有router导入
  const handleClick = () => {
    // 点击按钮执行的操作
    router.push('/digital-home/monitor');
  };
  const fetchData = async () => {
    const deviceId = await getAssetProfileId();
    console.log(deviceId);
  };
</script>

<template>
  <el-container style="width: 100vw; height: 100vh; display: flex; margin: 0; padding: 0">
    <div class="leftCon">
      <Left @title-change="handleTitleChange" />
    </div>
    <div class="centerCon" @click="handleOutsideClick">
      <!-- 新增全局标题 -->
      <div v-if="showGlobalTitle" class="global-title">
        {{ globalTitle || '锂电池工厂' }}
      </div>
      <!--      <button-->
      <!--        class="preview-btn"-->
      <!--        @mouseenter="handleMouseEnter"-->
      <!--        @mouseleave="handleMouseLeave"-->
      <!--        @click="handleClick"-->
      <!--      ></button>-->
      <!--      <div class="preview-txt" v-if="show_preview">预览</div>-->
      <center-header />
      <!--      <el-button @click="deleteAllDevices" id="basic">显示</el-button>-->
      <!--      <el-button @click="sceneClick" id="basic1">还原</el-button>-->
      <!-- Unity iframe -->
      <iframe
        ref="iframeRef"
        :src="iframeSrc"
        style="width: 64.1vw; height: 91vh; margin-top: 5vh; position: absolute; border: none"
      ></iframe>
    </div>
    <!-- </el-container> -->
    <div class="rightCon">
      <Right />
    </div>
  </el-container>
</template>

<style scoped>
  .preview-btn {
    right: 23.6vw;
    top: 6vh;
    position: absolute;
    width: 2vw;
    height: 2vw;
    z-index: 2;
  }

  .preview-txt {
    right: 23.65vw;
    top: 5vh;
    font-size: 16px;
    position: absolute;
    color: white;
    z-index: 2;
  }

  .leftCon {
    width: 18vw;
    height: 100vh;
    /* background: red; */
  }

  .leftHead :deep(.el-header) {
    background-color: #b3c0d1;
    color: #333;
    height: 5vh;
    width: 20vw;
  }

  .leftCon :deep(.sidebar) {
    width: 4vw;
    height: 95vh;
    /* background: #ebd50e; */
  }

  .leftCon :deep(.main-content) {
    width: 14vw;
    height: 95vh;
    /* background: #21eb0e; */
  }

  .centerCon {
    width: 64vw;
    height: 91vh;
  }

  .rightCon {
    width: 18vw;
    height: 100vh;
    background: #1e2430;
  }

  .rightCon :deep(.el-header) {
    /* background-color: #115bbb; */
    color: #333;
    height: 5vh;
    width: 18vw;
    padding: 0;
  }

  .rightCon :deep(.el-main) {
    padding: 0;
    height: 95vh;
  }

  :deep(.el-menu) {
    border-right: 0 !important;
  }

  #basic {
    z-index: 1;
    margin-top: 100px;
    position: absolute;
  }

  #basic1 {
    z-index: 1;
    margin-top: 150px;
    position: absolute;
  }

  .global-title {
    color: #fff;
    font-size: 1.4rem;
    font-weight: 500;
    text-align: center;
    letter-spacing: 1px;
    background: #1e2430 !important;
  }
</style>
